package com.liukai.todo_android.presenter;

import com.liukai.todo_android.call_back.IDeleteScheduleCallBack;
import com.liukai.todo_android.common.api.TodoAPI;
import com.liukai.todo_android.common.base.BasePresenter;
import com.liukai.todo_android.common.constants.ScheduleConst;
import com.liukai.todo_android.common.utils.RetrofitManager;
import com.liukai.todo_android.entity.Resp;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/17 9:44 上午
 * @description：删除待办相关的请求
 * @modified By：
 * @version: $
 */
public class DeleteSchedulePresenter extends BasePresenter<IDeleteScheduleCallBack> {

    public void deleteSchedule(Long id) {
        deleteScheduleById(id);
    }

    private void deleteScheduleById(Long id) {

        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        TodoAPI todoAPI = retrofit.create(TodoAPI.class);
        Call<Resp> deleteTask = todoAPI.deleteScheduleById(id);
        deleteTask.enqueue(new Callback<Resp>() {
            @Override
            public void onResponse(Call<Resp> call, Response<Resp> response) {
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    requestSuccess(response);
                } else {
                    requestFailure(response);
                }
            }

            @Override
            public void onFailure(Call<Resp> call, Throwable t) {
                requestFailure(t);
            }
        });

    }

    private void requestFailure(Throwable t) {
        mCallBack.deleteError(Resp.err(ScheduleConst.DELETE_SCHEDULE_FAILED_NO_INTERNET));
    }

    private void requestFailure(Response<Resp> response) {
        mCallBack.deleteError(Resp.err(ScheduleConst.DELETE_SCHEDULE_FAILED));
    }

    private void requestSuccess(Response<Resp> response) {
        Resp body = response.body();
        if (body.getCode() == ScheduleConst.DELETE_SCHEDULE_SUCCESS.getCode()) {
            mCallBack.deleteSuccess(body);
            return;
        }
        mCallBack.deleteError(body);
    }

}
